package ymos.mytracker.utli;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GetServerInfo {
	private static byte[] queryPacket;
	private static DatagramSocket socket;
	static {
		List<Byte> data = new ArrayList<>();
		for(int i=0;i<4;i++) {
			data.add((byte) 0xff);
		}		
		for(byte i :"TSource Engine Query".getBytes()) {
			data.add(i);
		}
		data.add((byte) 0x0);
		byte[] arr = new byte[data.size()];
		for(int i=0;i<arr.length;i++) {
			arr[i]=data.get(i);
		}
		queryPacket = arr;
	}
	
	public static ServerInfo connect(String ip,int port) throws IOException {
		socket = new DatagramSocket();
		socket.setSoTimeout(5000);
		socket.send(getPacket(queryPacket,ip,port));
		byte[] buf = new byte[1000];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		socket.receive(packet);
		//System.out.println(packet.getAddress());
		buf = Arrays.copyOf(packet.getData(), packet.getLength());
		return getServerInfo(buf,ip,port);
	}
	
	private static ServerInfo getServerInfo(byte[] data,String ip,int port) throws UnsupportedEncodingException {
		if(data.length<8) return null;
		boolean bool =data[4]==73&&data[5]==17;
		if(!bool)return null;
		ServerInfo info = new ServerInfo();
		info.setIp(ip);
		info.setPort(port);
		int temp=6;
		int point=0;
		boolean stop=false;
		for(int i=0;i<data.length;i++) {
			if(data[i]==0) {
				byte p[] = new byte[i-temp];
				System.arraycopy(data, temp, p, 0, i-temp);
				temp=i+1;
				String str = new String(p,"UTF-8");
				switch(point) {
					case 0:info.setServerName(str);break;
					case 1:info.setMap(str);break;
					case 2:info.setGameType(str);break;
					case 3:info.setGame(str);break;
					case 4:if(p.length>=4) {
						info.setMinPlayer((int)p[2]);
						info.setMaxPlayer((int)p[3]);
						stop=true;
					};break;
					case 5:if(p.length!=0) {
						info.setMinPlayer(0);
						info.setMaxPlayer((int)p[p.length-1]);
					}
				}
				point++;
				//System.out.println(Arrays.toString(p));
				//System.out.println(new String(p,"UTF-8"));
			}
			if(stop) {
				break;
			}
		}
		return info;
	}
	
	private static DatagramPacket getPacket(byte[] data,String ip,int port) throws UnknownHostException {
		return new DatagramPacket(data, data.length, InetAddress.getByName(ip),port);
	}
}
